const axios = require('axios');
const { ipcMain } = require('electron');

// 创建 axios 实例
const instance = axios.create({
  baseURL: process.env.VITE_API_URL,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
});

// 请求拦截器
instance.interceptors.request.use(
  (config) => {
    // 从本地存储获取 token
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
instance.interceptors.response.use(
  (response) => {
    return response;
  },
  (error) => {
    if (error.response) {
      switch (error.response.status) {
        case 401:
          // 发送消息给渲染进程，通知需要刷新 token 或跳转到登录页
          ipcMain.emit('auth-error', {
            type: 'token-expired',
            message: 'Token 已过期，请重新登录'
          });
          break;
        case 403:
          ipcMain.emit('auth-error', {
            type: 'permission-denied',
            message: '权限不足'
          });
          break;
        default:
          break;
      }
    }
    return Promise.reject(error);
  }
);

module.exports = instance;